// pages/notifications/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: 1,
    formats: {},
    placeholder: '开始输入...',
    content: '',
    title: '',
    titleMsg: '',
    edit: 'no',
    publishText: '提交通知',
    fileList: [],
    disabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ status: options.status, edit: options.edit });
    if (options.status == 2) {
      wx.setNavigationBarTitle({
        title: '创建公告',
      })
      this.setData({ publishText: '提交公告' });
    };
    if(wx.getStorageSync(`editnotificationTitle${this.data.status}`)) {
      this.setData({ title: wx.getStorageSync(`editnotificationTitle${this.data.status}`) });
    }
    wx.hideShareMenu();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.editorCtx = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  titleChange(e) {
    this.setData({ title: e.detail.value });
    if (this.data.titleMsg) this.setData({ titleMsg: '' });
    wx.setStorageSync(`editnotificationTitle${this.data.status}`, e.detail.value);
  },

  onEditorReady(e) {
    const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      if (wx.getStorageSync(`editnotificationContent${that.data.status}`)) {
        that.editorCtx.setContents({
          html: wx.getStorageSync(`editnotificationContent${that.data.status}`),
          success: function() {
            console.log('设置内容成功');
          },
          fail: function(err) {
            console.log('设置内容失败', err);
          }
        });
      }
    }).exec()
  },

  onInput(e) {
    this.setData({ content: e.detail.html });
    wx.setStorageSync(`editnotificationContent${this.data.status}`, e.detail.html);
  },

  onBlur(e) {
    // this.setData({ content: e.detail.html });
    this.editorCtx.blur();
  },

  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)
  },

  toolbar_indent() {
    this.editorCtx.format('textIndent', '2em')
  },

  onStatusChange(e) {
    const formats = e.detail
    console.log(formats);
    this.setData({ formats })
  },

  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },

  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },

  removeFormat() {
    this.editorCtx.removeFormat()
  },

  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },

  uploadOpen: function (e) {
    this.setData({
      isUpload: true,
      fileLength: this.data.fileList.length
    });
  },

  uploadClose: function () {
    this.setData({
      isUpload: false,
    });
  },

  receivingData: async function (val) {
    this.setData({
      fileList: [...this.data.fileList, val.detail]
    });
  },

  removeImage(e) {
    const arr = this.data.fileList;
    const index = e.currentTarget.dataset.index
    arr.splice(index, 1);
    this.setData({ fileList: arr });
  },

  publish() {
    if(this.data.disabled) return;
    if (!this.data.title) {
      this.setData({ titleMsg: '请输入标题' });
      return;
    }
    const picture = this.data.fileList.join(",");
    this.setData({ disabled: true });
    const that = this;
    wx.request({
      url: `${app.globalData.baseUrl}/api/notice/saveNotice`,
      method: "POST",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      data: {
        title: this.data.title,
        details: this.data.content,
        status: this.data.status,
        picture
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({ details: '', title: '' });
          if(wx.getStorageSync(`editnotificationTitle${this.data.status}`)) {
            wx.removeStorageSync(`editnotificationTitle${this.data.status}`);
          }
          if(wx.getStorageSync(`editnotificationContent${this.data.status}`)) {
            wx.removeStorageSync(`editnotificationContent${this.data.status}`);
          }
          wx.redirectTo({
            url: `/pages/notifyList/index?status=${this.data.status}&edit=${this.data.edit}`,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: 'title',
        })
      },
      complete: () => {
        setTimeout(() => {
          that.setData({ disabled: false });
        },1000)
      }
    })
  },
  preview(e) {
    let currentUrl = this.data.fileList;
    let index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: currentUrl[index], // 当前显示图片的http链接
      urls: this.data.fileList // 需要预览的图片http链接列表
    });
  },
})